package templates

import (
	"io/ioutil"
	"os"
	"path"
	"strings"
	"text/template"
)


type FileController struct {
	EntityName string
	ViewName string
}

func CreateViewController(){
	m := make(map[string]bool)
	infos, err := ioutil.ReadDir("controllers")
	if err!=nil{
		panic(err)
	}

	for _,v:=range infos{
		if v.IsDir() {
			continue
		}
		baseName := getBaseName(v.Name())
		baseName = strings.TrimSuffix(baseName,"Controller")
		m[baseName] = true
	}

	infos , err = ioutil.ReadDir("views")
	names:=make([]FileController,0)
	for _,v:=range infos{
		if v.IsDir(){
			continue
		}
		name := getBaseName(v.Name())
		names = append(names,FileController{
			EntityName:strings.Title(name),
			ViewName:name,
		})
		if _,ok := m[name];ok{
			continue
		}else{
			createTplFile(getBaseName(v.Name()))
		}
	}
	createRouterTpl(names)
}
func createTplFile(name string){
	parseFiles, err := template.ParseFiles("templates/viewTpl.txt")
	if err!=nil{
		panic(err)
	}
	file ,err := os.OpenFile("controllers/"+name +"Controller.go", os.O_CREATE|os.O_WRONLY, 0755)
	if err!=nil{
		panic(err)
	}
	fileName := strings.ToUpper(name[0:1]) +name[1:]
	controller := FileController{fileName,name}
	parseFiles.Execute(file,controller)
}

func getBaseName(name string)string{
	ext := path.Ext(name)
	return strings.TrimSuffix(name,ext)
}

func createRouterTpl(names []FileController){
	parseFiles, err := template.ParseFiles("templates/routerTpl.txt")
	if err!=nil{
		panic(err)
	}
	file ,err := os.OpenFile("temp/router.go", os.O_CREATE|os.O_WRONLY, 0755)
	parseFiles.Execute(file,names)
}